package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDataVo;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
/**
 * 设备管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-18
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper,Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private IoTDAClient client;

    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        //设置条数
        listProductsRequest.setLimit(50);
        //发起请求
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if(response.getHttpStatusCode() != 200){
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        //存储到redis
        List<ProductSummary> products = response.getProducts();
        redisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST).set(JSONUtil.toJsonStr(products));

    }
    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //从redis中查询数据
        String s = redisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST).get();
        if (s!=null) {//解析数据，并返回
            List<ProductVo> productVos = JSONUtil.toList(s, ProductVo.class);
            return productVos;
        }
        //如果数据为空，则返回一个空集合
        return List.of();
    }




@Override
public void registerDevice(DeviceDto dto) {
    // 查询设备名称是否重复
    LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(Device::getDeviceName,dto.getDeviceName());
    if (this.count(queryWrapper)>0) {
        throw new BaseException("设备名称重复");
    }

    // 查询设备标识是否重复
    queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(Device::getNodeId,dto.getNodeId());
    if (this.count(queryWrapper)>0) {
        throw new BaseException("设备标识重复");
    }

    // 查询同一个位置是否绑定了相同的产品
    //设备类型   具体位置  productKey
    queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(Device::getLocationType,dto.getLocationType());
    queryWrapper.eq(Device::getBindingLocation,dto.getBindingLocation());
    queryWrapper.eq(Device::getProductKey,dto.getProductKey());
    if (this.count(queryWrapper)>0) {
        throw new BaseException("同一个位置绑定了相同的产品");
    }

    // 调用IOT接口注册设备（注意设备deviceSecret需要自己生成）
    AddDeviceRequest request = new AddDeviceRequest();
    AddDevice body = new AddDevice();
    // body.setDeviceId(""); //IOT自动生成的
    body.setNodeId(dto.getNodeId());
    body.setDeviceName(dto.getDeviceName());
    body.setProductId(dto.getProductKey());
    AuthInfo authInfo = new AuthInfo(); //秘钥
    String secret = RandomUtil.randomString(32);
    authInfo.setSecret(secret); //秘钥
    body.setAuthInfo(authInfo);
    body.setDescription(dto.getDeviceDescription());
    request.setBody(body);
    AddDeviceResponse response = client.addDevice(request);
    if (response.getHttpStatusCode()!=201) {
        throw new BaseException("IOT设备添加失败");
    }
    String deviceId = response.getDeviceId();

    // 本地存储设备
    Device device = BeanUtil.toBean(dto, Device.class);
    // device.setId(0L);
    device.setIotId(deviceId);  //设备id 是IOT返回的
    device.setSecret(secret);

    this.save(device);
}
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        // IOT查询
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if (response.getHttpStatusCode()!=200) {
            throw new BaseException("IOT设备查询失败");
        }
        // 本地查询
        Device device = this.getOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId,iotId));
        if (device==null) {
            throw new BaseException("设备不存在");
        }

        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);

        //设备状态
        deviceDetailVo.setDeviceStatus(response.getStatus());

        String activeTimeStr = response.getActiveTime();// 2025-06-01T08:24:24.349Z
        // 把字符串转成LocalDateTime
        LocalDateTime parse = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
        // DateTimeZoneConverter是今天资料中提供的一个工具类
        LocalDateTime activeTime = DateTimeZoneConverter.utcToShanghai(parse);
        deviceDetailVo.setActiveTime(activeTime);



        return deviceDetailVo;
    }

    @Override
    public List<DeviceDataVo>queryServiceProperties(String iotId) {

        List<DeviceDataVo> list = new ArrayList<>();


        // IOT查询数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode()!=200) {
            throw new BaseException("IOT设备查询失败");
        }

        List<DeviceShadowData> shadowList = response.getShadow();
        if(CollUtil.isNotEmpty(shadowList)){



            DeviceShadowData deviceShadowData = shadowList.get(0);
            DeviceShadowProperties reported = deviceShadowData.getReported();
            String eventTimeStr = reported.getEventTime();//20250601 T 08 24 34 Z
            LocalDateTime eventTimeUTC = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
            LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeUTC);

            Object properties = reported.getProperties();
            JSONObject jsonObject = JSONUtil.parseObj(properties);
            jsonObject.forEach((key,value)->{
                DeviceDataVo deviceDataVo = new DeviceDataVo();
                deviceDataVo.setFunctionId(key);
                deviceDataVo.setEventTime(eventTime);
                deviceDataVo.setValue(value);
                list.add(deviceDataVo);
            });
        }
        return list;
    }


}
